package com.zhekou.util;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: cjp
 * Date: 2009-4-7
 * Time: 14:30:45
 */
public class HttpClientUtil {
    static DefaultHttpClient httpClient = new DefaultHttpClient();

    public static String get(String url) throws Exception {
        return get(url, "UTF-8");
    }

    public static String get(String url, String encoding) throws Exception {
        DefaultHttpClient httpClient2 = new DefaultHttpClient();
        httpClient2.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000 * 5);
        httpClient2.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000 * 5);
        HttpGet httpGet = new HttpGet(url);
        HttpResponse res = httpClient2.execute(httpGet);
        return getContent(res, encoding);
    }

    public static String get(String url, String host, String referer, String encoding, DefaultHttpClient client) {
        //System.out.println("get url = "+url);
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Host", host);
        httpGet.setHeader("Referer", referer);
        httpGet.setHeader("Accept", "*/*");
        httpGet.setHeader("Accept-Language", "zh-cn");
        httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=gb2312");
        httpGet.setHeader("UA-CPU", "x86");
        httpGet.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; InfoPath.2; CIBA)");

        try {
            HttpResponse res = client.execute(httpGet);
            return getContent(res, encoding);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String get(String url, String encoding, DefaultHttpClient client) {
        //System.out.println("get url = "+url);
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Accept", "*/*");
        httpGet.setHeader("Accept-Language", "zh-cn");
        httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=gb2312");
        httpGet.setHeader("UA-CPU", "x86");
        httpGet.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; InfoPath.2; CIBA)");

        try {
            HttpResponse res = client.execute(httpGet);
            return getContent(res, encoding);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


//    public static String post(String url, StringEntity se, String host, String referer, String encoding) throws Exception {
//        System.out.println("post url=" + url);
//        //System.out.println("post para=" + se);
//        HttpPost httpPost = new HttpPost(url);
//        httpPost.setEntity(se);
//        httpPost.setHeader("Host", host);
//        httpPost.setHeader("Referer", referer);
//        httpPost.setHeader("Accept", "*/*");
//        httpPost.setHeader("Accept-Language", "zh-cn");
//        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
//        httpPost.setHeader("UA-CPU", "x86");
//        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; InfoPath.2; CIBA)");
//
///*        BufferedReader reader = new BufferedReader(new InputStreamReader(se.getContent(), "utf-8"));
//        String line = null;
//        while ((line = reader.readLine()) != null) {
//          System.out.println(line);
//        }*/
//        HttpResponse response = httpClient.execute(httpPost);
//        return getContent(response, encoding);
//    }

    public static String post(String url, StringEntity se, String host, String referer, String encoding, DefaultHttpClient defaultHttpClient) {

        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(se);
            httpPost.setHeader("Host", host);
            httpPost.setHeader("Referer", referer);
            httpPost.setHeader("Accept", "**/*//*");
            httpPost.setHeader("Accept-Language", "zh-cn");
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.setHeader("UA-CPU", "x86");
            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; InfoPath.2; CIBA)");
            HttpResponse response = defaultHttpClient.execute(httpPost);
            return getContent(response, encoding);
        } catch (Exception e) {
            System.out.println("http post error:" + e.getMessage());
        }
        return "";
    }

    public static HttpResponse postResponse(String url, StringEntity se, String host, String referer, String encoding, DefaultHttpClient defaultHttpClient) {
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(se);
            httpPost.setHeader("Host", host);
            httpPost.setHeader("Referer", referer);
            httpPost.setHeader("Accept", "**/*//*");
            httpPost.setHeader("Accept-Language", "zh-cn");
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.setHeader("UA-CPU", "x86");
            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; InfoPath.2; CIBA)");
            HttpResponse response = defaultHttpClient.execute(httpPost);
            return response;
        } catch (Exception e) {
            System.out.println("http post get response error:" + e.getMessage());
        }
        return null;
    }


    public static String getContent(HttpResponse res, String encoding) {
        try {
            HttpEntity ent = res.getEntity();
            String result = "";
            if (ent != null) {
                result = IOUtils.toString(ent.getContent(), encoding);
                EntityUtils.consume(ent);
            }
            return result;
        } catch (Exception e) {
            System.out.println("http getContent error " + e.getMessage());
        }
        return "";
    }

    public static InputStream getStream(String url) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Accept-Encoding", "gzip, deflate");
        HttpResponse res = httpClient.execute(httpGet);
        return res.getEntity().getContent();
    }

    public static InputStream getStream(String url, DefaultHttpClient client) throws Exception {

        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; InfoPath.2; CIBA)");
        //httpGet.setHeader("Referer", "http://reg.126.com/regmail126/userRegist.do?action=fillinfo");
        HttpResponse res = client.execute(httpGet);
        return res.getEntity().getContent();
    }


    public static InputStream getStream(String url, DefaultHttpClient client, String host, String referer) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; InfoPath.2; CIBA)");
        httpGet.setHeader("Referer", referer);
        httpGet.setHeader("Host", host);
        HttpResponse res = client.execute(httpGet);
        return res.getEntity().getContent();
    }

    public static List<NameValuePair> getPostParam(String id, String result) {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        Document document = Jsoup.parse(result);
        String relashForm = document.getElementById(id).outerHtml();
        document = Jsoup.parse(relashForm);
        Elements elements = document.getElementsByTag("input");
        for (Element element : elements) {
            //System.out.println(element.attr("name") + "=" + element.attr("value"));
            nameValuePairs.add(new BasicNameValuePair(element.attr("name"), element.attr("value")));
        }
        return nameValuePairs;
    }

    public static List<NameValuePair> getPostParam(Map<String, String> data) {
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        for (Map.Entry entry : data.entrySet()) {
            if (StringUtils.isNotBlank(entry.getKey().toString())) {
                //System.out.println(entry.getKey().toString()+"=" + entry.getValue().toString());
                nameValuePairList.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()));
            }
        }
        return nameValuePairList;
    }

    public static Map<String, String> getMapData(String id, String result) {
        Map<String, String> map = new HashMap<String, String>();
        Document document = Jsoup.parse(result);
        String relashForm = document.getElementById(id).outerHtml();
        document = Jsoup.parse(relashForm);
        String actionURL = document.getElementById(id).attr("action");
        map.put("actionURL", actionURL);
        //System.out.println("action="+document.getElementById(id).attr("action"));
        Elements elements = document.getElementsByTag("input");
        for (Element element : elements) {
            //System.out.println(element.attr("name") + "=" + element.attr("value"));
            map.put(element.attr("name"), element.attr("value"));
        }
        return map;
    }

    public static String post(String url, String encoding, Map<String, String> data, String referer, String host, DefaultHttpClient client) {
        try {
            HttpPost httpPost = new HttpPost(url);
            if (StringUtils.isNotBlank(referer)) {
                httpPost.setHeader("Referer", referer);
                httpPost.setHeader("Host", host);
            }
            if (data != null && data.size() > 0) {
                List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
                for (Map.Entry entry : data.entrySet()) {
                    nameValuePairList.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList, "utf-8"));
            }
            HttpResponse res = client.execute(httpPost);
            return getContent(res, encoding);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static HttpResponse getResponse(String url, DefaultHttpClient client) {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Accept", "*/*");
        httpGet.setHeader("Accept-Language", "zh-cn");
        httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=gb2312");
        httpGet.setHeader("UA-CPU", "x86");
        httpGet.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; InfoPath.2; CIBA)");
        try {
            HttpResponse res = client.execute(httpGet);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static HttpResponse getResponse(String url, String host, String referer, DefaultHttpClient client) {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Host", host);
        httpGet.setHeader("Referer", referer);
        httpGet.setHeader("Accept", "*/*");
        httpGet.setHeader("Accept-Language", "zh-cn");
        httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=gb2312");
        httpGet.setHeader("UA-CPU", "x86");
        httpGet.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; InfoPath.2; CIBA)");

        try {
            HttpResponse res = client.execute(httpGet);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
